package com.itheima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpService empService;
    @Override
    public PageResult<Clazz> getClazzPage(ClazzQueryParam param) {
        Page<Clazz> page = new Page<Clazz>(param.getPage(), param.getPageSize());
        page = lambdaQuery().like(param.getName() != null && !param.getName().isEmpty(), Clazz::getName, param.getName())
                .between(param.getBegin() != null && param.getEnd() != null, Clazz::getEndDate, param.getBegin(), param.getEnd())
                .page(page);

        List<Clazz> clazzs = page.getRecords();
        //获取所有班级的班主任id
        List<Long> empIds = clazzs.stream().map(clazz -> clazz.getMasterId()).collect(Collectors.toList());
        //批量查询这些班主任的信息
        if(!empIds.isEmpty()){
            List<Emp> emps = empService.listByIds(empIds);
            //将员工名称封装到班级对象中
            clazzs.forEach(clazz->{
                emps.forEach(emp->{
                    if(clazz.getMasterId()!=null&&clazz.getMasterId().equals(emp.getId())){
                        clazz.setMasterName(emp.getName());
                    }
                });
            });
        }
        clazzs.forEach(clazz->{
            if (LocalDate.now().isBefore(clazz.getBeginDate())){
                clazz.setStatus("未开班");
            }
            if(LocalDate.now().isAfter(clazz.getEndDate())){
                clazz.setStatus("已结课");
            }
            if(LocalDate.now().isAfter(clazz.getBeginDate())&&LocalDate.now().isBefore(clazz.getEndDate())){
                clazz.setStatus("在读");
            }
        });
        PageResult<Clazz> result = new PageResult<>(page.getTotal(), clazzs);
        return result;
    }
}
